import React, { useEffect, useState } from 'react';
import { Input, Select, Button, Pagination, message, Modal } from 'antd';
import { HomeOutlined, CommentOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import TopNavBar from './components/TopNavBar';
import SubNavBar from './components/SubNavBar';
import TaskCard from './components/TaskCard';
import { fetchTaskList, terminateTask } from './service';
import { Task, PageState } from './types';
import { PAGINATION_CONFIG, SPECIAL_TOPIC_ITEMS, STATUS_ITEMS } from './constants';
import styles from './index.less';

const { Search } = Input;
const { Option } = Select;

// 初始状态
const initialState: PageState = {
  tasks: [],
  pagination: {
    currentPage: PAGINATION_CONFIG.defaultCurrent,
    totalItems: 0,
    pageSize: PAGINATION_CONFIG.defaultPageSize,
    totalPages: 0
  },
  filters: {
    specialTopics: [],
    statuses: []
  },
  activeNav: 'initiated',
  activeStatus: 'active',
  specialTopic: 'all',
  searchKeyword: '',
  loading: false
};

const TaskListPage: React.FC = () => {
  const [state, setState] = useState<PageState>(initialState);
  
  // 初始化加载数据
  useEffect(() => {
    loadTaskList();
  }, []);

  // 加载任务列表
  const loadTaskList = async (page = 1) => {
    setState(prev => ({ ...prev, loading: true }));
    try {
      const response = await fetchTaskList({
        page,
        pageSize: state.pagination.pageSize,
        status: state.activeStatus,
        specialTopic: state.specialTopic,
        keyword: state.searchKeyword
      });
      
      if (response.success && response.data) {
        const { tasks = [], pagination = initialState.pagination, filters = initialState.filters } = response.data;
        setState(prev => ({
          ...prev,
          tasks,
          pagination,
          filters,
          loading: false
        }));
      } else {
        setState(prev => ({ ...prev, loading: false }));
      }
    } catch (error) {
      console.error('加载任务列表失败:', error);
      message.error('加载任务列表失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 处理导航变化
  const handleNavChange = (nav: string) => {
    setState(prev => ({ ...prev, activeNav: nav }));
    // 实际项目中可能需要根据导航重新加载数据
  };

  // 处理状态变化
  const handleStatusChange = (status: string) => {
    setState(prev => ({ ...prev, activeStatus: status }));
    loadTaskList(1); // 切换状态后重新加载第一页数据
  };

  // 处理专题特性筛选变化
  const handleSpecialTopicChange = (value: string) => {
    setState(prev => ({ ...prev, specialTopic: value }));
    loadTaskList(1);
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setState(prev => ({ ...prev, searchKeyword: value }));
    loadTaskList(1);
  };

  // 处理分页变化
  const handlePageChange = (page: number) => {
    loadTaskList(page);
  };

  // 处理强行终止
  const handleTerminate = (taskId: string) => {
    Modal.confirm({
      title: '确认强行终止',
      icon: <ExclamationCircleOutlined />,
      content: `确定要终止任务 ${taskId} 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const result = await terminateTask(taskId);
          if (result.success) {
            message.success('任务已终止');
            // 重新加载当前页数据
            loadTaskList(state.pagination.currentPage);
          } else {
            message.error(result.message || '操作失败');
          }
        } catch (error) {
          console.error('终止任务失败:', error);
          message.error('终止任务失败');
        }
      }
    });
  };

  // 处理查看详情
  const handleViewDetail = (taskId: string) => {
    // 实际项目中这里可能会跳转到详情页
    message.info(`查看任务详情: ${taskId}`);
  };

  return (
    <div className={styles.container}>
      {/* 顶部导航 */}
      <TopNavBar
        activeNav={state.activeNav}
        onNavChange={handleNavChange}
        userName="伍罡"
        userCode="80293464"
      />
      
      {/* 二级导航 */}
      <SubNavBar
        activeStatus={state.activeStatus}
        statuses={STATUS_ITEMS}
        onStatusChange={handleStatusChange}
      />
      
      {/* 功能区 */}
      <div className={styles['function-bar']}>
        <div className={styles['filter-group']}>
          <Select 
            value={state.specialTopic} 
            onChange={handleSpecialTopicChange}
            className={styles.select}
          >
            {SPECIAL_TOPIC_ITEMS.map(item => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
          
          <Search
            placeholder="输入关键词搜索"
            onSearch={handleSearch}
            enterButton
            className={styles.search}
          />
        </div>
        
        <Button 
          type="link" 
          icon={<HomeOutlined />} 
          className={styles['home-link']}
        >
          首页
        </Button>
      </div>
      
      {/* 卡片列表 */}
      <div className={styles['card-container']}>
        {state.tasks.map(task => (
          <div className={styles['card-wrapper']} key={task.id}>
            <TaskCard 
              task={task}
              onTerminate={handleTerminate}
              onDetail={handleViewDetail}
            />
          </div>
        ))}
      </div>
      
      {/* 分页 */}
      <div className={styles.pagination}>
        <div className={styles['page-info']}>
          共 {state.pagination.totalItems} 条
        </div>
        <Pagination
          current={state.pagination.currentPage}
          total={state.pagination.totalItems}
          pageSize={state.pagination.pageSize}
          onChange={handlePageChange}
          showSizeChanger={false}
          size="small"
        />
      </div>
      
      {/* 客服按钮 */}
      <div className={styles['service-btn']}>
        <CommentOutlined />
      </div>
    </div>
  );
};

export default TaskListPage;
